package com.gao.controller;

import org.springframework.stereotype.Controller;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * @Projectname springboot-redis
 * @Filename SecKillController
 * @Author an
 * @Data 2022/8/19 9:10
 * @Description TODO
 */
@Controller
public class SecKillController {

    //秒杀过程
    public static boolean doSecKill(String uid,String prodid){

        //1. uid和proid非空判断
        if (uid==null || prodid==null){
            return false;
        }

        //2. 连接redis
//        Jedis jedis = new Jedis("192.168.195.129", 6379);

        //通过连接池得到jedis对象
        JedisPool jedisPoolInstance = JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis = jedisPoolInstance.getResource();


        //3. 拼接key
        //3.1 库存key
        String kcKey = "sk:"+prodid+":qt";
        //3.2 秒杀成功用户key
        String userKey = "sk:"+prodid+":user";

        //监视库存
        jedis.watch(kcKey);


        //4. 获取库存，如果库存为空，秒杀还没有开始
        String kc = jedis.get(kcKey);
        if (kc==null){
            System.out.println("秒杀还没开始，等待");
            jedis.close();
            return false;
        }

        //5. 判断用户是否重复秒杀操作
        boolean sismember = jedis.sismember(userKey, uid);
        if (sismember){
            System.out.println("秒杀成功，只能秒杀一次");
            jedis.close();
            return false;
        }
        //6. 库存的数量小于1，秒杀结束
        if (Integer.parseInt(kc)<=0){
            System.out.println("秒杀结束");
            jedis.close();
            return false;
        }

        //7. 秒杀过程

        //使用事务
        Transaction multi = jedis.multi();
        //组队操作
        multi.decr(kcKey);
        multi.sadd(userKey,uid);

        //执行
        List<Object> results = multi.exec();

        if (results==null || results.size()==0){
            System.out.println("秒杀失败");
            jedis.close();
            return false;
        }

        //7.1 库存-1

        jedis.decr(kcKey);
        //7.2 把秒杀成功用户添加到清单里面
        jedis.sadd(userKey,uid);

        System.out.println("秒杀成功");
        jedis.close();

        return true;
    }
}
